﻿using System.ComponentModel.Composition;
using System.Windows;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using System.Windows.Input;

namespace Sentio.CodeReview.Editor
{
    
    public sealed class CodeReviewMouseProcessor : MouseProcessorBase
    {
        private readonly IWpfTextView _textView = null;
        public static bool ReviewMode = false;
        
        public CodeReviewMouseProcessor(IWpfTextView textView)
        {
            _textView = textView;
        }

        public override void PostprocessMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e)
        {
            base.PostprocessMouseLeftButtonUp(e);
            Microsoft.VisualStudio.Text.ITextDocument document = null;
            if (ReviewMode && _textView.Selection.IsActive && 
                !_textView.Selection.IsEmpty)
            {
                if (_textView != null)
                {
                    document = _textView.TextDataModel.DocumentBuffer.Properties[typeof(Microsoft.VisualStudio.Text.ITextDocument)] 
                        as Microsoft.VisualStudio.Text.ITextDocument;
                    if (document != null || document.TextBuffer != null)
                    {
                        AddCodeComment addComment = new AddCodeComment(
                                _textView.Selection.StreamSelectionSpan.Start.Position.Position,
                                _textView.Selection.StreamSelectionSpan.End.Position.Position, document.FilePath);

                        addComment.WindowStartupLocation = WindowStartupLocation.Manual;
                        addComment.Left = e.GetPosition(_textView.VisualElement).X + _textView.ViewportLeft + 100;
                        addComment.Top = e.GetPosition(_textView.VisualElement).Y + _textView.ViewportTop + 100;
                        addComment.ShowDialog();
                    }
                }
            }
        }

        public override void PostprocessMouseDown(MouseButtonEventArgs e)
        {
            base.PostprocessMouseDown(e);

            
        }
    }

    [Export(typeof(IMouseProcessorProvider))]
    [Name("CodeReviewerMouseProcessor")]
    [ContentType("text")]
    [TextViewRole(PredefinedTextViewRoles.Interactive)]
    public sealed class CodeReviewMouseProcessorProvider : IMouseProcessorProvider
    {
        public IMouseProcessor GetAssociatedProcessor(IWpfTextView wpfTextView)
        {
            return new CodeReviewMouseProcessor(wpfTextView);
        }
    }
}
